# -*- coding: UTF-8 -*-
import signal
import time
import schedule

from lj_tool import tool_cache, tool_id, tool_sys

tool_run_g = {
    "is_golbal_stop": False
}

__run_dict = {}
__run_stop = {}


def do(task, time):
    schedule.every(time).seconds.do(task)


# time:每天的时间，字符串
def do_everyday(task, time):
    schedule.every().day.at(time).do(task)


@tool_cache.lj_wrapper_cache("tool_run_start", 60 * 60 * 24 * 30)
def start():
    LJWhileRun(lambda: schedule.run_pending()).start()


class LJWhileRun():
    def __init__(self, fun) -> None:
        self.fun = fun
        self.is_stop = False

    def start(self):
        while not self.is_stop and not tool_run_g.get("is_golbal_stop"):
            # print("LJ - 循环执行...")
            self.fun()

    def stop(self):
        self.is_stop = True


def init_new_run(fun):
    """创建新的运行函数"""
    key = tool_id.gen_id_str()
    __run_dict[key] = fun
    return key


def start_run(key):
    t_run = __run_dict.get(key)
    if t_run:
        __run_stop[key] = False
        while not __run_stop.get(key) and not tool_run_g.get("is_golbal_stop"):
            t_run()


async def start_async_run(key):
    t_run = __run_dict.get(key)
    if t_run:
        __run_stop[key] = False
        while not __run_stop.get(key) and not tool_run_g.get("is_golbal_stop"):
            await t_run()


def stop_run(key):
    __run_stop[key] = True
    print(f"停止循环[{key}][{__run_stop[key]}]...")


def stop():
    print(f"LJ - 停止全局循环...")
    tool_run_g["is_golbal_stop"] = True


tool_sys.exit_listen(stop)
